/*
 * 北京慧点科技有限公司XCOA产品。
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的。
 * @Date: 2021年04月23日
 * @Copyright: Copyright 2020 © Smartdot Technologies Co., Ltd.
 */
package com.zodiac.alioth.web.controller.zf;

import org.bson.types.Binary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @author <a href="mailto:lishuren@smartdot.com">lishuren</a>
 * @version 1.0, 2024年11月11日
 */

@RestController
@RequestMapping("/test")
public class ApplyController {
    
    @Autowired
    private MongoTemplate mongoTemplate;
    
    @GetMapping("/ss")
    public String ss(){
        return "Hello World";
    }
    
    
    @PostMapping("/upload")
    public Result upLoadImage(@RequestParam(value = "file") MultipartFile file) {
        if(file.isEmpty()){
            return new Result(false,"400","文件为空");
        }
        String filename = file.getOriginalFilename();
        try {
            ImageFile img = new ImageFile().setId(String.valueOf(System.currentTimeMillis())).setFilename(filename).setCreatedTime(LocalDateTime.now()).setContent(new Binary(file.getBytes())).setContentType(file.getContentType()).setSize(file.getSize());
            ImageFile save = mongoTemplate.save(img);
            String url = "http://localhost:9528/alioth/test/download/"+save.getId();
            return new Result(true,"200",url);
        } catch (IOException e) {
            return new Result (false,"500","系统异常");
        }
    }
    
    
    @GetMapping(value = "/download/{id}",produces = {MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE})
    public byte[] downloadImage(@PathVariable("id")String id) {
        byte[] data = null;
        ImageFile img = mongoTemplate.findById(id, ImageFile.class);
        if(img!=null){
            data = img.getContent().getData();
        }
        return data;
    }

}
